<script setup lang="ts">
import { tableConfig } from './config/table-config';
import baseTable from '@/components/base-ui/base-table/index.vue';
import { doAddEquipment } from '@/api/modeling/equipment/index';
import { handleDelKey, checkRepeat, RepeatMsg } from '@/utils';
import { message } from '@/components/q-message/message';
import { doGetWorkshopList } from '@/api/base/workshop/index';
import useEmit from '@/hooks/useEmitter';
import usePageSave from '@/hooks/usePageSave';
import type { WorkshopRecords } from '@/api/base/workshop/model/type';
import type { AddEquipmentData } from '@/api/modeling/equipment/model/type';
import type { IWorkshop } from '../../type';

const { loading, modalOk, modalSlotRef } = useModal();

defineOptions({
    name: 'EquipmentAdd'
});

const STORE_KEY = 'equipmentAddData'; // store数据的key
const { startRecording, isUpdate } = useEmit(STORE_KEY); // 页面标签路由关闭二次确认事件监听

useRecordData(modalSlotRef, STORE_KEY, isUpdate, startRecording); // 复制相关

/**
 * @: 新增提交
 */
const handleSubmit = async () => {
    const tableData: (AddEquipmentData & IWorkshop)[] = modalSlotRef.value?.getSaveData();
    const value = tableData.map(item => {
        const data = {
            ...item,
            workshopName: item.workshop.workshopName,
            workshopId: item.workshop.id
        };
        return handleDelKey(data, ['id', 'workshop']);
    });
    try {
        const msg = checkRepeat(value, ['equipmentNumber']);

        if (msg) {
            const { line, value } = msg;
            RepeatMsg({ line, value, label: '设备编码' });
            return;
        }
        const res = await doAddEquipment(value);
        if (res) {
            message.success('新增成功！');
            return res;
        }
    } catch (error) {
        console.log(error);
    }
};

/**
 * @: 车间
 */
const selectLoading = ref(false);
const itemCodeOption = ref<WorkshopRecords[]>();
const itemCodeRemoteMethod = async (query: string) => {
    selectLoading.value = true;
    try {
        const { data } = await doGetWorkshopList({ keyword: query, size: 200, current: 1 }, 1);
        if (data) {
            itemCodeOption.value = data.records;
        }
    } catch (error) {
        console.log('-------', error);
    }
    selectLoading.value = false;
};

/**
 * @: 点击保存
 */
const handleOk = async () => {
    try {
        await modalOk(handleSubmit);
        usePageSave('/equipment');
    } catch (e) {
        console.log(e);
    }
};

onBeforeMount(() => {
    itemCodeRemoteMethod('');
});
</script>
<template>
    <q-page>
        <base-table
            ref="modalSlotRef"
            :table-config="tableConfig"
            show-fullscreen
            add-table-row
            open-sticky
        >
            <!-- 保存/取消 -->
            <template #tableHeadEnd>
                <q-submit-button
                    size="default"
                    :hide-label="true"
                    align="right"
                    :horizontal="true"
                    :cancel-button="false"
                    :loading="loading"
                    @save="handleOk"
                />
            </template>

            <!-- 车间 -->
            <template #workshop="{ row, item, validFn }">
                <el-select
                    v-model="row.workshop"
                    filterable
                    remote
                    :loading="selectLoading"
                    reserve-keyword
                    remote-show-suffix
                    :remote-method="(e: string) => itemCodeRemoteMethod(e)"
                    value-key="id"
                    popper-class="push-select"
                    placeholder="请选择"
                    @focus="
                        (e: any) => {
                            itemCodeRemoteMethod('');
                            validFn.handleFocus(e, row, {
                                config: item
                            });
                        }
                    "
                    @change="validFn.setValidErrorVisible(false)"
                    @blur="validFn.setValidErrorVisible(false)"
                >
                    <el-option
                        v-for="item in itemCodeOption"
                        :key="item.id"
                        :label="item.workshopName + ' - ' + item.workshopCode"
                        :value="item"
                    />
                    <template #footer>
                        <q-push-button @click="$router.push('/Workshop')" />
                    </template>
                </el-select>
            </template>
        </base-table>
    </q-page>
</template>

<style lang="scss" scoped></style>
